//
//  OpenSDK_BindMobileView.m
//  OpenSDK
//
//  Created by 涂俊 on 2018/7/26.
//  Copyright © 2018年 WYHT. All rights reserved.
//

#import "OpenSDK_BindMobileView.h"
#import "OpenSDK_SmsView.h"
#import "OpenSDK_LoginManager.h"
#import "OpenSDK_PayManager.h"
#import "OpenSDK_UIManager.h"
#import "OpenSDK_DataManager.h"
#import "OpenSDK_LocalRecord.h"
#import "OpenSDK_Toast.h"
#import "OpenSDK_PullDownView.h"
#import "OpenSDK_CountryCell.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_UIUtil.h"
#import "OpenSDK_StatisticsManager.h"

@interface OpenSDK_BindMobileView () <UITableViewDataSource>

@end

@implementation OpenSDK_BindMobileView

{
    UIButton *countryBtn;
}

#pragma mark - 生命周期函数
- (void)viewDidLoad {
    [super viewDidLoad];
    _bgView.backgroundColor = UIColor.whiteColor;
    _bgView.layer.cornerRadius = 10;
    _bgView.layer.masksToBounds = true;
    // Do any additional setup after loading the view.
    // 输入法上移
    self.keyboardExtraMargin = 30;
    
    // 输入框内容缩进
    self.mobileInputView.delegate = self;
    self.mobileInputView.edgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    // 输入框左边是国家区号按钮
    countryBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, self.mobileInputView.frame.size.height)];
    [countryBtn setImage:[UIImage imageNamed:@"op_icon_history"] forState:UIControlStateNormal];
    countryBtn.titleLabel.font = [UIFont systemFontOfSize: 14.0];
    [countryBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [countryBtn addTarget:self action:@selector(didClickCountryBtn:) forControlEvents:UIControlEventTouchUpInside];
    // 加载本地保存的当前国家区号
    if([[OpenSDK_LocalRecord getInstance] getLocalValueForKey:OpenSDK_L_COUNTRY_CODE]!=nil) {
        [self resetCountryCodeInfo];
    } else {
        NSString *countryNumber = [[[OpenSDK_DataManager getInstance] getCountryCodeFromCurMachine] objectForKey:OpenSDK_S_COUNTRY_NUMBER];
        [countryBtn setTitle:countryNumber forState:UIControlStateNormal];
    }
    // 文字左，图片右
    CGFloat imageWidth = countryBtn.imageView.bounds.size.width + 7;
    CGFloat labelWidth = countryBtn.titleLabel.bounds.size.width + 7;
    countryBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
    countryBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth, 0, imageWidth);
    // 添加到输入框中
    [self.mobileInputView setEdgeView:countryBtn width:60 horizontalPadding:0 verticalPadding:0 isLeft:YES];
    
    // 点击背景，收起输入法
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didHideKeyboard:)]];
    [self.bgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didHideKeyboard:)]];
    
    // 登录跳转过来的绑定，是返回按钮；支付跳转过来的绑定，是关闭按钮
    if (self.order) {
        self.backBtn.hidden = YES;
        self.closeBtn.hidden = NO;
    } else {
        self.backBtn.hidden = NO;
        self.closeBtn.hidden = YES;
    }
    
    //判断是否强制实名认证
    OpenSDK_AccountRecord *curAccount = [[OpenSDK_DataManager getInstance] getCurAccount];
    if (curAccount != nil && curAccount.needMobile == 2) {
        self.backBtn.hidden = YES;
        self.closeBtn.hidden = YES;// 强制绑定手机，不显示关闭按钮
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - tableview回调
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[OpenSDK_DataManager getInstance] countryCodeInfo].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableDictionary *dic=[[[OpenSDK_DataManager getInstance] countryCodeInfo] objectAtIndex:indexPath.row];
    OpenSDK_CountryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OpenSDK_CountryCell" forIndexPath:indexPath];
    [cell.layer setBorderWidth:0.5];
    [cell.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    cell.nameView.text = [dic objectForKey:OpenSDK_S_COUNTRY_NAME];
    cell.numberView.text = [dic objectForKey:OpenSDK_S_COUNTRY_NUMBER];
    return cell;
}

#pragma mark - 私有方法
-(void) resetCountryCodeInfo {
    if([[[OpenSDK_DataManager getInstance] countryCodeInfo] count]==0)
        return;
    NSString *localCountryCode=[[OpenSDK_LocalRecord getInstance] getLocalValueForKey:OpenSDK_L_COUNTRY_CODE];
    NSMutableDictionary *dic;
    NSString *countryNumber;
    for( int i=0; i<[[OpenSDK_DataManager getInstance] countryCodeInfo].count; i++) {
        dic=[[[OpenSDK_DataManager getInstance] countryCodeInfo] objectAtIndex:i];
        if([[dic objectForKey:OpenSDK_S_COUNTRY_CODE] isEqualToString:localCountryCode]) {
            countryNumber=[dic objectForKey:OpenSDK_S_COUNTRY_NUMBER];
        }
    }
    if(countryNumber==nil) {
        localCountryCode=[[[[OpenSDK_DataManager getInstance] countryCodeInfo] objectAtIndex:0] objectForKey:OpenSDK_S_COUNTRY_CODE];
        countryNumber=[[[[OpenSDK_DataManager getInstance] countryCodeInfo] objectAtIndex:0] objectForKey:OpenSDK_S_COUNTRY_NUMBER];
        [[OpenSDK_LocalRecord getInstance] saveData:OpenSDK_L_COUNTRY_CODE value:localCountryCode];
    }
    [countryBtn setTitle:countryNumber forState:UIControlStateNormal];
}

#pragma mark - 按钮监听
- (void)didClickCountryBtn:(id)sender {
    //收起键盘
    [self didHideKeyboard:sender];
    
    OpenSDK_PullDownView *menuView = [OpenSDK_PullDownView pullMenuAnchorView:sender
                                                                tableDelegate:self
                                                                    menuWidth:self.mobileInputView.frame.size.width
                                                                  cellNibName:@"OpenSDK_CountryCell"
                                                          cellReuseIdentifier:@"OpenSDK_CountryCell"];
    menuView.menuCellHeight = self.mobileInputView.frame.size.height;
    menuView.menuMaxHeight = 3 * self.mobileInputView.frame.size.height;//默认显示3格
    menuView.place = AnchorPlaceLeft;
    menuView.blockSelectedMenu = ^(NSInteger menuRow) {
        // 点击国家区号
        NSLog(@"click----->%ld", (long)menuRow);
        NSMutableDictionary *dic=[[[OpenSDK_DataManager getInstance] countryCodeInfo] objectAtIndex:menuRow];
        NSString *curCountryCode=[dic objectForKey:OpenSDK_S_COUNTRY_CODE];
        [[OpenSDK_LocalRecord getInstance] saveData:OpenSDK_L_COUNTRY_CODE value:curCountryCode];
        [self resetCountryCodeInfo];
    };
    [menuView show:NO];
}

- (IBAction)didClickBackBtn:(id)sender {
    // 跳转到快捷登录
    [[OpenSDK_UIManager getInstance] showNextUIWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_QuickLoginView"];
}

- (IBAction)didClickCloseBtn:(id)sender {
    // 关闭界面
    [[OpenSDK_UIManager getInstance] closeUI];
    if (self.order) {
        // 上报支付取消统计
        [[OpenSDK_StatisticsManager getInstance] collectPayCancelWithCpOrderId:self.order.appData detail:OPENSDK_STATS_DETAIl_PAY_CANCEL_BIND];
        // 如果是支付进来的绑定手机，关闭页面，需要回调支付取消
        [[OpenSDK_PayManager getInstance] callbackPayCancel];
    }
}

- (IBAction)didClickNextBtn:(id)sender {
    //收起键盘
    [self didHideKeyboard:sender];
    
    NSString *mobile = self.mobileInputView.text;
    if (mobile == nil || mobile.length == 0) {
        [[[OpenSDK_iToast makeText:@"手机号不能为空"] setDuration:2000] show];
        return;
    }
    //判断手机号格式
    NSString *regex = @"[0-9]+";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if (mobile.length < 11 || ![mobile hasPrefix:@"1"] || (![predicate evaluateWithObject:mobile])) {
        [[[OpenSDK_iToast makeText:@"手机号格式错误"] setDuration:2000] show];
        return;
    }
    // 跳转到验证码界面
    UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
    OpenSDK_SmsView *vc = (OpenSDK_SmsView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_SmsView"];
    vc.mobile = mobile;
    vc.isBind = YES;
    vc.order = self.order;
    [self.navigationController pushViewController:vc animated:NO];
}

@end
